package io.renren.modules.sys.controller;


import io.renren.common.annotation.Login;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.form.LoginForm;
import io.renren.modules.sys.entity.SmsEntity;
import io.renren.modules.study.entity.StudentEntity;
import io.renren.modules.sys.entity.TokenEntity;
import io.renren.modules.sys.entity.UserEntity;
import io.renren.modules.study.service.StudentService;
import io.renren.modules.sys.service.TokenService;
import io.renren.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录接口
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api")
@Api(tags="登录接口")
public class ApiLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private StudentService studentService;

    @GetMapping("getEdition")
    @ApiOperation("获取版本")
    public R Edition() {
        return tokenService.getEdition();
    }

    @GetMapping("getNewEdition")
    @ApiOperation("获取最新版本")
    public R getNewEdition() {

        return tokenService.getNewEdition();
    }




    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form) {
        //表单校验
        ValidatorUtils.validateEntity(form);
        //用户登录
        return userService.login(form);
    }

    @PostMapping("QQlogin")
    @ApiOperation("QQ登录")
    public R QQlogin(@RequestBody Map QQData) {
        //QQUid寻找
        TokenEntity token = new TokenEntity();
        String msg = "";
        int code = 100;
        String qqUid = (String) QQData.get("qqUid");
        UserEntity userEntity = userService.QQlogin(qqUid);
        //找到QQ,绑定了手机号
        if (userEntity != null) {
            token = tokenService.createToken(userEntity.getUserId());
            Map<String, Object> map = new HashMap<>(2);
            map.put("token", token);
            map.put("isAuthentication", userEntity.getIsAuthentication());
            map.put("expire", token.getExpireTime().getTime() - System.currentTimeMillis());
            map.put("isOneLogin",userEntity.getIsOneLogin());
            //找不到信息，注册后，返回客户信息
            if(userEntity.getStatus()==1){
                return R.ok("此用户已被禁用",101);
            }
            if(0 == userEntity.getIsOneLogin()){
                //修改成已经登陆过 1
                Map m = new HashMap();
                m.put("qqUid",qqUid);
                userService.updateIsOneLogin(m);
            }
            return R.ok(msg, code).put("data", map);
        } else {
            msg = "用户未注册";
            code = 101;
            return R.ok(msg, code);
        }


    }

    @PostMapping("WxLogin")
    @ApiOperation("微信登陆")
    public R WxLogin(@RequestBody UserEntity userEntity) {
        /*//手机号和openId不可能会传来空的 所以直接判断当前手机号的用户的openid在数据库中是否存在
        Long userId = userService.getUserIdByMobile(userEntity.getMobile());  //获取当前用户的userId
        UserEntity user = userService.getUserByUserId(userId);  //获取当前用户
        if(user.getOpenId() == null){
            //第一次微信登陆  将openId设置进数据库中
            userEntity.setUserId(userId);
            userService.updateOpenIdByuserId(userEntity);
            return R.ok("登陆成功",100);
        }else {
            //非第一次登录微信 判断openId是否正确
            //获取当前用户的openId
            String openId = userEntity.getOpenId();
            String openIdInSQL = user.getOpenId();
            if (openId.equals(openIdInSQL)) {
                //openId比对成功 是正确的openId
                return R.ok("登陆成功",100);
            }
            return R.error(101,"微信信息错误，请重新登录");
        }*/

        //首先判断这个openId在数据库中是否存在
        /*Long userId = userService.getUserIdByMobile(userEntity.getMobile());  //获取当前用户的userId
        UserEntity user = userService.selectUserByOpenId(userEntity);
        if(user.getOpenId() != null){
            //数据库中有这个用户
            //判断这个用户是否绑定了手机号
            if(user.getMobile()!=null){
                //该用户绑定了手机号
                String openId = userEntity.getOpenId();
                String openIdInSQL = user.getOpenId();
                if (openId.equals(openIdInSQL)) {
                    //openId比对成功 是正确的openId
                    return R.ok("登陆成功",100);
                }
                return R.error(101,"微信信息错误，请重新登录");
            }else {
                //该openId的用户没有绑定手机号
                //发送验证码到前台传来的手机上
                userService.sendSms(userEntity.getMobile());
                //判断验证码是否是正确的
                String code = userService.getCodeByMobile(userEntity.getNewMobile());
                if(userEntity.getNewCode().equals(code)){
                    //验证码正确 将手机号设置到这个数据库该用户上
                    UserEntity user1 = new UserEntity();
                    user1.setMobile(userService.updateMobileByOpenId(userEntity.getOpenId()));
                    userService.updateMobileByUserId(user1);
                    return R.ok("登陆成功",100);
                }else {
                    //验证码比对失败
                    return R.error(101,"验证码错误");
                }
            }
        }else {
            //数据库中没有这个openId的用户  那就创建这个用户
        }

        return R.error(101,"微信信息错误，请重新登录");*/
        TokenEntity token = new TokenEntity();
        //String openId = userEntity.getOpenId();
        UserEntity userEntity1 = userService.getUserByOpenId(userEntity);
        String msg = "";
        int code = 100;
        if (userEntity1 != null) {
            //有这个用户
            Long userId = userService.getUserIdByMobile(userEntity1.getMobile());
            token = tokenService.createToken(userId);
            Map<String, Object> map = new HashMap<>(2);
            map.put("token", token);
            map.put("isAuthentication", userEntity1.getIsAuthentication());
            map.put("isOneLogin",userEntity.getIsOneLogin());
            //map.put("expire", token.getExpireTime().getTime() - System.currentTimeMillis());
            //找不到信息，注册后，返回客户信息
            if(userEntity1.getStatus()==1){
                return R.ok("此用户已被禁用",101);
            }
            if(0 == userEntity.getIsOneLogin()){
                //修改成已经登陆过 1
                Map m = new HashMap();
                m.put("openId",userEntity1.getOpenId());
                userService.updateIsOneLogin(m);
            }
            return R.ok(msg, code).put("data", map);
        } else {
            return R.error(101, "用户未注册");
        }
    }


    @PostMapping("Codelogin")
    @ApiOperation("验证码登录")
    public R Codelogin(@RequestBody Map QQData) {
        //QQUid寻找
        TokenEntity token = new TokenEntity();
        String msg = "";
        int code = 100;
        String qqUid = (String) QQData.get("qqUid");
        UserEntity userEntity = userService.QQlogin(qqUid);
        //找到QQ,绑定了手机号
        if (userEntity != null) {
            token = tokenService.createToken(userEntity.getUserId());
        } else {
            msg = "用户未注册";
            code = 101;
        }
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", token);
        map.put("isAuthentication", userEntity.getIsAuthentication());
        map.put("expire", token.getExpireTime().getTime() - System.currentTimeMillis());
        //找不到信息，注册后，返回客户信息


        return R.ok(msg, code)
                .put("data", map);
    }

    /**
     * 绑定手机号
     */
    /*@PostMapping("bangdingMobile")
    @ApiOperation("绑定手机号")
    public R bangdingMobile(@RequestBody UserEntity userEntity){
        return
    }*/

    /**
     * 判断手机号
     */
    @GetMapping("judgeMobile/{mobile}")
    @ApiOperation("判断手机号")
    public R judgeMobile(@PathVariable("mobile") String mobile){

        //UserEntity userEntity=userService.queryByMobile(mobile);
        //UserEntity user = new UserEntity();
        //user.setMobile(mobile);
        List userList = userService.selectUserByMobile(mobile);
        if(userList.size()==0) {
            return R.ok("此手机号未注册",100);
        }else {
            UserEntity userEntity = (UserEntity) userList.get(0);
            if(userEntity.getOpenId()==null&&userEntity.getQqUid()==null) {
                return R.ok("此手机号已注册", 101);
            }else if(userEntity.getOpenId()!=null&&userEntity.getQqUid()==null){
                return R.ok("此手机号已注册,微信已绑定，QQ未绑定", 102);
            }else if(userEntity.getOpenId()==null&&userEntity.getQqUid()!=null){
                return R.ok("此手机号已注册,微信未绑定，QQ已绑定", 103);
            }else {
                return R.ok("此手机号已注册,微信，QQ都绑定", 104);
            }
        }
    }


        /**
         * 通过验证码登陆
         * @param
         * @return
         */
        @PostMapping("loginByCode")
        @ApiOperation("通过手机验证码登陆")
        public R loginByCode (@RequestBody SmsEntity smsEntity){
            String code = smsEntity.getCode();
            String mobile = smsEntity.getMobile();
            String codeInSQL = userService.getCodeByMobile(mobile);
            Long userId = userService.getUserIdByMobile(mobile);
            //System.out.println("code:"+code+"   "+ "codeInSQL:"+codeInSQL+"   "+"mobile:"+mobile+"  "+"userId:"+ userId);
            if (code.equals(codeInSQL) && userId != null) {
                UserEntity user = userService.getUserByUserId(userId);
                TokenEntity token = tokenService.createToken(userId);
                user.setToken(token.getToken());
                return R.ok("登陆成功", 100).put("data", user);
            }
            if (userId == null) {
                return R.error(101, "请注册后登陆");
            }
            if (!code.equals(codeInSQL)) {
                return R.error(101, "验证码错误");
            }
            return R.error(101, "网络故障，请重试");
        }

        @Login
        @PostMapping("logout")
        @ApiOperation("退出")
        public R logout (@ApiIgnore @RequestAttribute("userId") Long userId){
            tokenService.expireToken(userId);
            return R.ok();
        }

        @Login
        @GetMapping("authentication")
        @ApiOperation("认证")
        public R Authentication (@ApiIgnore @RequestAttribute("userId") Long userId){


            //  String phone=userService.selectMobileByUserId(userId);
            //  StudentEntity studentEntity=studentService.getStudentByPhone(phone);
            return studentService.authentication(userId);
        }


        /**
         * 根据手机号获取userId  根据id对字段进行修改
         */
        @Login
        @PostMapping("updateStudentMessage")
        @ApiOperation("修改学生联系人，紧急联系人，身份证号，高考分数")
        public R updateStudentMessage (@RequestBody StudentEntity studentEntity, @RequestAttribute("userId") Long userId)
        {
            studentEntity.setUserId(Math.toIntExact(userId));
            int count = studentService.updateStudentMessage(studentEntity);
            if (count != 0) {
                return R.ok("修改成功", 100);
            }
            return R.error(101, "修改失败，请检查网络问题");

        }

        /**
         * 查询数据库中的四个字段是否为空
         */
        @Login
        @PostMapping("selectStudentIsNull")
        @ApiOperation("查询数据库中的四个字段是否为空")
        public R selectStudentIsNull (@RequestBody StudentEntity studentEntity){
            int userId = studentEntity.getUserId();
            StudentEntity studentEntity1 = studentService.selectStudentIsNull(userId);
            return R.ok("查询该学生学生联系人，紧急联系人，身份证号，高考分数成功", 100).put("data", studentEntity1);
        }

        /**
         * 绑定QQ或者微信的接口
         */
        @Login
        @PostMapping("bangDingQQOrWechat")
        @ApiOperation("绑定QQ或者微信的接口")
        public R bangDingQQOrWechat (@RequestBody UserEntity userEntity) throws UnsupportedEncodingException {
            String token = userEntity.getToken();
            Long userId = tokenService.getUserIdByToken(token);
            /*if(userId == null ){

            }*/
            String mobile = userService.getUserByUserId(userId).getMobile();
            userEntity.setMobile(mobile);
            //判断是否已经绑定过了 绑定后的需要解除绑定才行
            List userList = userService.selectUserByMobile(mobile);
            UserEntity user = (UserEntity) userList.get(0);
            if (user.getOpenId() == null && userEntity.getOpenId() != null) {
                //绑定微信
                userService.updateUserByMobile(userEntity);
                if (user.getHeadImg() == null && userEntity.getHeadImg() != null && user.getNickName() == null && userEntity.getNickName() != null) {
                    //修改头像和昵称
                    userEntity.setNickName(new String(user.getNickName().getBytes("utf-8")));
                    //userEntity.setNickName(new String(user.getNickNameB(),"UTF-8"));
                    userService.updateImaAndNickByMobile(userEntity);
                    return R.ok("微信绑定成功", 100);
                }

            } else if (user.getQqUid() == null && userEntity.getQqUid() != null) {
                //绑定QQ
                userService.updateUserByMobile(userEntity);
                if (user.getHeadImg() == null && userEntity.getHeadImg() != null && user.getNickName() == null && userEntity.getNickName() != null) {
                    //修改头像和昵称
                    userService.updateImaAndNickByMobile(userEntity);
                    return R.ok("QQ绑定成功", 100);
                }

            }
            return R.error(101, "请解除绑定后再重新绑定");

        }


        /**
         * 判断是否绑定QQ或者微信
         */
        @Login
        @GetMapping("isBangDingQQOrWechat")
        @ApiOperation("判断是否绑定QQ或者微信")
        public R isBangDingQQOrWechat (@RequestParam String token){
           // String token = userEntity.getToken();
            Long userId = tokenService.getUserIdByToken(token);
            String mobile = userService.getUserByUserId(userId).getMobile();
            List userList = userService.selectUserByMobile(mobile);
            UserEntity user = (UserEntity) userList.get(0);
            //判断
            if (user.getQqUid() == null && user.getOpenId() == null) {
                //都没绑定
                //userService.updateIsBangDingQQOrWechatByMobile(userEntity);
                return R.ok("QQ和微信都未绑定", 100).put("QQ", 0).put("WeChat", 0);
            } else if (user.getQqUid() == null && user.getOpenId() != null) {
                //绑定了微信  通过手机号修改微信状态为1
                //userService.updateIsBangDingQQOrWechatByMobile(userEntity);
                return R.ok("只绑定了微信", 100).put("QQ", 0).put("WeChat", 1);
            } else if (user.getQqUid() != null && user.getOpenId() == null) {
                //绑定了微信  通过手机号修改微信状态为1
                //userService.updateIsBangDingQQOrWechatByMobile(userEntity);
                return R.ok("只绑定了QQ", 100).put("QQ", 1).put("WeChat", 0);
            } else if (user.getQqUid() != null && user.getOpenId() != null) {
                //绑定了微信  通过手机号修改微信状态为1
                //userService.updateIsBangDingQQOrWechatByMobile(userEntity);
                return R.ok("微信和QQ都绑定了", 100).put("QQ", 1).put("WeChat", 1);
            }
            return R.error(101, "网络故障请重试");
        }

    /**
     * 解除绑定
     */
    @Login
    @PostMapping("killBangDingQQOrWechat")
    @ApiOperation("解除绑定QQ或者微信")
    public R killBangDingQQOrWechat(@RequestBody UserEntity userEntity){
        Long userId = tokenService.getUserIdByToken(userEntity.getToken());
        userEntity.setUserId(userId);
        //if(userEntity.getQqUid() != null && !"".equals(userEntity.getQqUid())){
        if(userEntity.getNewCode().equals("1")){
            userService.updateIsBangDingQQOrWeChat(userEntity);  //修改为 字段为空 is为0
            return R.ok("解除QQ绑定成功",100);
        }else if (userEntity.getNewCode().equals("2")){
            userService.updateIsBangDingQQOrWeChat(userEntity);  //修改为 字段为空 is为0
            return R.ok("解除微信绑定成功",100);
        }
        return R.error(101, "网络故障请重试");
    }

    /**
     * 测试一波
     *//*
    @PostMapping("ceshi")
    @ApiOperation("测试一波")
    public R ceshi(@RequestBody Map map) throws UnsupportedEncodingException {
        Long userId = tokenService.getUserIdByToken((String) map.get("token"));
        //Byte[] o = userService.getNickNameById(userId);
       // user.setNickName(new String(user.getNickNameB(),"UTF-8"));
       UserEntity user =  userService.getUserByUserId(userId);

        return R.ok("查询成功",100).put("data",new String(user.getNickNameB(),"UTF-8"));
    }*/
}

